﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Dynamitey;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using org.apache.zookeeper.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Coldairarrow.Entity.Interface.YDOrdersDTO.Orders.Delivery;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class OL_Rep_AMZNewPrdReturnsInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters;
        public OL_Rep_AMZNewPrdReturnsInterfaceBusiness()
        {
            this.InterfaceName = "电商新品退货统计";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();


            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                //数据库连接
                ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
                SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

                //获取此接口的所有API信息
                this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
                Base_InterfaceOption queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
                Base_InterfaceOption insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
                Base_InterfaceOption upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
                Base_InterfaceOption deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置
                //获取需要统计几个月的数据
                int month = queryOption.ExcInterval;

                //获取退货
                //List<FBAReturnOrder> returnOrderList = SqlDb.GetListBySql<FBAReturnOrder>(@$"SELECT * FROM SD_LX_FBAReturnOrder WHERE return_date_locale >='{dateAMZ}'");
                //获取退货
                //List<FBMReturnOrder> returnOrderList_FBM = SqlDb.GetListBySql<FBMReturnOrder>(@$"SELECT * FROM SD_LX_FBMReturnOrder WHERE return_date >='{dateAMZ}'");

                //获取One_Link亚马逊MSKU信息
                AMZ_MSKUInterfaceBusiness aMZ_MSKU = new AMZ_MSKUInterfaceBusiness();
                aMZ_MSKU.Filters.Clear();
                aMZ_MSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "685aa0b5a31d84c7f659fa16", DataType = 30, SpliceType = 1, FilterType = 2, Value = "10001" }//只查询亚马逊的MSKU
           );
                List<AMZ_MSKU> AMZ_MSKUList = await aMZ_MSKU.QueryAsync<AMZ_MSKU>(aMZ_MSKU.queryOption, aMZ_MSKU.tableField, aMZ_MSKU.SqlDb);
                AMZ_MSKUList.ForEach(x =>
                {
                    //SKU
                    List<AssTable> table = x.sku_lock.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.sku_lock_T = table[0];
                    x.sku_lock = x.sku_lock_T.IsNullOrEmpty() ? "" : x.sku_lock_T.sid;
                });


                //获取One_Link SKU信息
                OL_LocalSKUInterfaceBusiness localSKU = new OL_LocalSKUInterfaceBusiness();
                localSKU.Filters.Clear();
                localSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开始700天前到现在的数据
           );
                List<LocalSKU> localSKUList = await localSKU.QueryAsync<LocalSKU>(localSKU.queryOption, localSKU.tableField, localSKU.SqlDb);


                List<Rep_AMZNewPrdReturns> sourceData = new List<Rep_AMZNewPrdReturns>();
                if (AMZ_MSKUList.Count > 0)
                {
                    //用MSKU获取第一单后的三个月的销量退货
                    //var mskuList = AMZ_MSKUList.GroupBy(x => x.seller_sku).Select(x => x.First());
                    localSKUList.ForEach(sku =>
                    {
                        //获取本地SKU对应MSKU的列表
                        var mskuList = AMZ_MSKUList.Where(x => sku.RowId == x.sku_lock);
                        var msku = "";
                        //获取第一个订单的订单时间
                        List<AMZOrderDetail> date = null;
                        if (!mskuList.IsNullOrEmpty() && mskuList.Count() > 0)
                        {
                            msku = string.Join(",", mskuList.Select(x => "'" + x.seller_sku + "'"));
                            date = SqlDb.GetListBySql<AMZOrderDetail>(@$"SELECT TOP 1 purchase_date_local FROM SD_LX_AMZOrderDetail WHERE  seller_sku IN ({msku}) AND quantity_ordered>0 ORDER BY purchase_date_local");
                        }


                        if (!date.IsNullOrEmpty() && date.Count > 0)
                        {
                            Rep_AMZNewPrdReturns rep = new Rep_AMZNewPrdReturns();
                            //获取需要查询的时间
                            string firstDate = date.First().purchase_date_local.ToDateTime().ToString("yyyy-MM-dd");
                            string lastDate = firstDate.ToDateTime().AddMonths(month).ToString("yyyy-MM-dd");
                            rep.FristDate = firstDate;
                            //rep.MSKU = msku.RowId;
                            rep.SKU = sku.RowId;
                            //获取订单
                            List<AMZOrderDetail> orderList = SqlDb.GetListBySql<AMZOrderDetail>(@$"SELECT purchase_date_local,amazon_order_id,seller_sku,quantity_ordered FROM SD_LX_AMZOrderDetail(NOLOCK) 
                             WHERE  seller_sku IN ({msku}) AND  purchase_date_local>='{firstDate}' AND purchase_date_local<='{lastDate}' AND quantity_ordered>0");
                            rep.LastDate = orderList.OrderBy(x => x.purchase_date_local).Last().purchase_date_local;
                            //设置销量
                            rep.SalesQty = orderList.Sum(x => x.quantity_ordered.ToInt());
                            string orders = string.Join(",", orderList.Select(x => "'" + x.amazon_order_id + "'"));
                            rep.ReturnQty = 0;
                            //获取FBA退货
                            List<FBAReturnOrder> returnOrderList = SqlDb.GetListBySql<FBAReturnOrder>(@$"SELECT order_id,sku,quantity FROM SD_LX_FBAReturnOrder(NOLOCK) WHERE order_id IN ({orders}) AND sku IN ({msku})");
                            if (!returnOrderList.IsNullOrEmpty() && returnOrderList.Count > 0)
                            {
                                rep.ReturnQty = returnOrderList.Sum(x => x.quantity.ToInt());
                            }

                            //获取FBM退货
                            List<FBMReturnOrder> returnOrderList_FBM = SqlDb.GetListBySql<FBMReturnOrder>(@$"SELECT order_id,seller_sku,return_quantity FROM SD_LX_FBMReturnOrder(NOLOCK) WHERE order_id IN ({orders}) AND seller_sku IN ({msku})");
                            if (!returnOrderList_FBM.IsNullOrEmpty() && returnOrderList_FBM.Count > 0)
                            {
                                rep.ReturnQty = rep.ReturnQty + returnOrderList_FBM.Sum(x => x.return_quantity);
                            }
                            rep.SKU_S = sku.SKU;
                            rep.ID = rep.SKU;
                            rep.MSKU = string.Join(",", orderList.Select(x => x.seller_sku).Distinct());
                            sourceData.Add(rep);
                        }
                    });

                }


                //获取目标数据
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开
            );
                List<Rep_AMZNewPrdReturns> targetData = await QueryAsync<Rep_AMZNewPrdReturns>(queryOption, tableField, SqlDb);
                foreach (var item1 in targetData)
                {
                    //SKU
                    List<AssTable> table = item1.SKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.SKU = table[0].sid;
                    else item1.SKU = "";
                    //MSKU
                    //table = item1.MSKU.ToObject<List<AssTable>>();
                    //if (!table.IsNullOrEmpty() && table.Count > 0) item1.MSKU = table[0].sid;
                    //else item1.MSKU = "";
                }
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<Rep_AMZNewPrdReturns> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<Rep_AMZNewPrdReturns>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<Rep_AMZNewPrdReturns> insertItem = sourceData.Except(targetData, new ComparerFromKey<Rep_AMZNewPrdReturns>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<Rep_AMZNewPrdReturns> deleteItem = targetData.Except(sourceData, new ComparerFromKey<Rep_AMZNewPrdReturns>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }


        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
